
/**
 * Content: Arrays类常用方法、数组转列表、复制数组
 * --------------------------------------------------
 * Java集合框架Arrays的常见方法: https://juejin.cn/post/6945262011072643109
 */

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class java_0405_class_Arrays {
    public static void main(String[] args) {

        // Arrays类常用方法
        System.out.println("--------------------Arrays类常用方法--------------------");

        // 新建一个数组
        int[] numbers = {1,2,4,6,3,5};

        // 基础类型 排序: Arrays.sort()
        Arrays.sort(numbers);

        // 数组转字符串: Arrays.toString()
        String arrStr = Arrays.toString(numbers);  // 输出: [1, 2, 3, 4, 5, 6]
        String arrStr2 = numbers.toString();       // 输出: [I@4554617c
        System.out.println("Arrays.toString(numbers): " + arrStr);
        System.out.println("numbers.toString(): " + arrStr2);

        // 自定义类 排序
        Student[] students = new Student[]{new Student("张三", 22), new Student("李四", 22), new Student("王五", 33)};
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                if (s1 == null || s2 == null) {
                    return 0;
                }
                return s1.getAge() - s2.getAge()==0 ? s1.getName().compareTo(s2.getName()) : s1.getAge()-s2.getAge();
            }
        });
        System.out.println(Arrays.toString(students));

        // 并行排序
        int[] numbers3 = {1,2,4,6,3,5};
        Arrays.parallelSort(numbers3);
        System.out.println(Arrays.toString(numbers3));

        // 二分查找 (使用二分查找之前需要先排序, 不然只会返回 -3)
        int[] numbers5 = {1,2,4,6,3,5};
        Arrays.sort(numbers5);
        int num5 = Arrays.binarySearch(numbers5, 3);
        System.out.println("3 的下标是: " + num5);

        // 数组转列表
        System.out.println("--------------------数组转列表--------------------");

        List<Object> list = Arrays.asList(numbers5);
        System.out.println("数组转列表, 得到List: " + list.toString());

        // 得到的 List 为定长的, 无法对其进行 添加 和 删除 操作, 会报错
//        list.add(12);

        // 复制数组
        System.out.println("--------------------复制数组--------------------");

        int[] number7 = Arrays.copyOf(numbers5, 3);
        System.out.println(Arrays.toString(numbers));

    }
}

class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}